package cn.codingjc.aurora.framework.schedule.core;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @auth: coding_jc
 * @date: 2023/11/2 23:14
 * @desc:
 */

@Slf4j
public class SchedulingRunnable implements Runnable{

    private String beanName;

    private String methodName;

    private Object params;

    private Object targetBean;

    private Method method;

    public SchedulingRunnable(String beanName, String methodName) {
        this(beanName, methodName, null);
    }

    public SchedulingRunnable(String beanName, String methodName, Object params) {
        this.beanName = beanName;
        this.methodName = methodName;
        this.params = params;
    }

    private void init(){
        try {
            targetBean = SpringUtil.getBean(beanName);

            if (ObjectUtil.isNotNull(params)) {
                method = targetBean.getClass().getDeclaredMethod(methodName, Object.class);
            } else {
                method = targetBean.getClass().getDeclaredMethod(methodName);
            }
            ReflectionUtils.makeAccessible(method);
        } catch (Exception e) {
            log.error("get target method error:", e);
        }
    }

    @Override
    public void run() {
        log.info("定时任务开始执行 - bean:{}, param:{}", beanName, params);
        long startTime = System.currentTimeMillis();

        try {
            if (ObjectUtil.isNotNull(params)) {
                method.invoke(targetBean, params);
            } else{
                method.invoke(targetBean);
            }
        } catch (Exception e) {
            log.error("定时任务执行异常 - bean:{}, param:{}, e:", beanName, params, e);
        }

        long endTime = System.currentTimeMillis();
        long time = endTime -startTime;
        log.info("定时任务执行结束 - bean:{}, param:{}, cost:{}", beanName, params, time);
    }
}
